'use strict';
const db = uniCloud.database()
const {
  Base64
} = require("base64")
exports.main = async (event, context) => {
  //event为客户端上传的参数
  console.log('event : ', event)
  let res = ''
  switch (event.class || event.title || event.openid || event._id) {
    case event.class:
      res = await db.collection("article").where({
        class: event.class
      }).get()
      res.data.forEach(function(obj) {
        delete obj.openid
      })
      break;
    case event.title:
      res = await db.collection("article").where({
        title: new RegExp(`${event.title}`)
      }).get()
      res.data.forEach(function(obj) {
        delete obj.openid
      })
      break;
    case event._id:
      res = await db.collection("article").where({
        _id: event._id
      }).get()
      delete res.data[0].openid
      res.data[0].comment.forEach(function(obj) {
        delete obj.openid
        if (obj.moreComment.length > 0) {
          obj.moreComment.forEach(function(o) {
            delete o.openid
          })
        }
      })
      break;
    case event.openid:
      let base = new Base64()
      res = await db.collection("article").where({
        openid: JSON.parse(base.decode(event.openid))
      }).get()
      break;
    default:
      break
  }
  //返回数据给客户端
  return res.data
};
